package com.nongcai159.mall.lib_common.base

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v7.app.AppCompatActivity

import com.nongcai159.mall.lib_common.utils.BarUtils
import com.nongcai159.mall.lib_common.utils.MLog

import java.lang.ref.WeakReference


/**
 * 普通Activity基类
 *
 *
 * Created by tanbiheng on 2018/11/26.
 */

abstract class BaseActivity : AppCompatActivity() {

    var isActivityFinish = false// UI是否关闭
    var isActivityForground = false// UI是否在后台
    private var action: BaseActivityAction? = null

    var mHandler: ActivityWeakReferenceHandler? = null

    /**
     * 绑定activity布局到窗口
     */
    abstract val contentView: Int

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        MLog.d("当前Activity:" + this.javaClass.toString())
        if (action == null) {
            action = BaseActivityAction()
        }
        action!!.onCreate(this)

        setContentView(contentView)

        BarUtils.setTransparentStatusBar(this, true)

        initActivity()
    }

    override fun onNewIntent(intent: Intent) {
        if (action == null) {
            action = BaseActivityAction()
        }
        action!!.onNewIntent(intent, this)
    }

    override fun onResume() {
        super.onResume()
        isActivityForground = true

        if (action == null) {
            action = BaseActivityAction()
        }
        action!!.onResume(this)
    }

    override fun onPause() {
        super.onPause()
        isActivityForground = false

        if (action == null) {
            action = BaseActivityAction()
        }
        action!!.onPause(this)
    }

    override fun onStop() {
        super.onStop()
        if (action == null) {
            action = BaseActivityAction()
        }
        action!!.onStop(this)
    }

    override fun onStart() {
        super.onStart()
    }

    override fun onDestroy() {
        super.onDestroy()

        isActivityFinish = true
        if (action == null) {
            action = BaseActivityAction()
        }
        action!!.onDestroy(this)

        if (mHandler != null) {
            mHandler!!.removeCallbacksAndMessages(null)
            mHandler = null
        }
    }

    override fun finish() {
        super.finish()
    }

    fun handleMyMessage(msg: Message) {

    }

    class ActivityWeakReferenceHandler(activity: BaseActivity) : Handler() {
        private val mActivity: WeakReference<BaseActivity>

        init {
            mActivity = WeakReference(activity)
        }

        override fun handleMessage(msg: Message) {
            if (mActivity.get() == null) {
                return
            }
            (mActivity.get() as BaseActivity).handleMyMessage(msg)
        }
    }

    /**
     * 初始化UI
     */
    abstract fun initActivity()

}
